package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.mapper.XcChooseCourseMapper;
import com.xuecheng.learning.mapper.XcCourseTablesMapper;
import com.xuecheng.learning.model.dto.MyCourseTableParams;
import com.xuecheng.learning.model.dto.XcChooseCourseDto;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.model.po.XcCourseTables;
import com.xuecheng.learning.service.XcChooseCourseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author xiao
 * @Date 2024/12/24 下午 2:29
 * @ClassName: XcChooseCourseServiceImpl
 * @Description: TODO
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class XcChooseCourseServiceImpl extends ServiceImpl<XcChooseCourseMapper, XcChooseCourse> implements XcChooseCourseService {

    @Resource
    private ContentServiceClient contentServiceClient;
    @Resource
    private XcChooseCourseMapper xcChooseCourseMapper;
    @Resource
    private XcCourseTablesMapper xcCourseTablesMapper;

    /**
     * @param userId
     * @param courseId
     * @return
     * @Desc: 添加选课
     */
    @Transactional
    @Override
    public XcChooseCourseDto addChooseCourse(String userId, Long courseId) {

        //使用OpenFeign远程调用查询数据库，是否有这个课程
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if (coursepublish == null) {
            throw new RuntimeException("课程未发布");
        }
        //课程是否收费
        String charge = coursepublish.getCharge();
        XcChooseCourse xcChooseCourse = null;
        //免费课程 添加选课记录，添加到我的课程表
        if ("201000".equals(charge)) {
            xcChooseCourse = addFreeCourse(userId, coursepublish);
            XcCourseTables xcCourseTables = addCourseTabls(xcChooseCourse);
        } else {
            //收费课程 添加到选课记录
            xcChooseCourse = addChargeCoruse(userId, coursepublish);
        }
        //先创建待返回的对象
        XcChooseCourseDto xcChooseCourseDto = new XcChooseCourseDto();
        BeanUtils.copyProperties(xcChooseCourse, xcChooseCourseDto);
        //获取学习资格
        XcCourseTablesDto learningStatus = getLearningStatus(userId, courseId);
        if (learningStatus == null) {
            xcChooseCourseDto.setLearnStatus("702002");//没有选课或选课后没有支付
            return xcChooseCourseDto;
        }
        xcChooseCourseDto.setLearnStatus(learningStatus.getLearnStatus());
        return xcChooseCourseDto;
    }


    //添加收费课程
    public XcChooseCourse addChargeCoruse(String userId, CoursePublish coursePublish) {
        //查询是否已经添加
        List<XcChooseCourse> courseList = xcChooseCourseMapper.selectList(new LambdaQueryWrapper<XcChooseCourse>()
                .eq(XcChooseCourse::getUserId, userId)
                .eq(XcChooseCourse::getCourseId, coursePublish.getId())
                .eq(XcChooseCourse::getOrderType, "700002") //收费课程
                .eq(XcChooseCourse::getStatus, "701002")); //待支付
        if (!courseList.isEmpty()) {
            return courseList.get(0);
        }
        //未添加 向XcChooseCourse表插入
        XcChooseCourse xcChooseCourse = XcChooseCourse.builder()
                .userId(userId)
                .courseId(coursePublish.getId())
                .courseName(coursePublish.getName())
                .coursePrice(0f)
                .companyId(coursePublish.getCompanyId())
                .orderType("700002") //收费课程
                .createDate(LocalDateTime.now())
                .validDays(365)
                .coursePrice(coursePublish.getPrice())
                .status("701002") //待支付
                .validtimeStart(LocalDateTime.now())
                .validDays(coursePublish.getValidDays())//有效期天数
                .validtimeEnd(LocalDateTime.now().plusDays(365))
                .remarks(coursePublish.getRemark())
                .build();
        int insert = xcChooseCourseMapper.insert(xcChooseCourse);
        if (insert <= 0) {
            throw new RuntimeException("课程添加失败");
        }
        return xcChooseCourse;

    }


    //添加免费课程,免费课程加入选课记录表、我的课程表
    private XcChooseCourse addFreeCourse(String userId, CoursePublish coursePublish) {
        //查询是否已经添加
        List<XcChooseCourse> courseList = xcChooseCourseMapper.selectList(new LambdaQueryWrapper<XcChooseCourse>()
                .eq(XcChooseCourse::getUserId, userId)
                .eq(XcChooseCourse::getCourseId, coursePublish.getId())
                .eq(XcChooseCourse::getOrderType, "700001") //免费课程
                .eq(XcChooseCourse::getStatus, "701001")); //选课成功
        if (!courseList.isEmpty()) {
            return courseList.get(0);
        }
        //未添加 向XcChooseCourse表插入
        XcChooseCourse xcChooseCourse = XcChooseCourse.builder()
                .userId(userId)
                .courseId(coursePublish.getId())
                .courseName(coursePublish.getName())
                .coursePrice(0f)
                .companyId(coursePublish.getCompanyId())
                .orderType("700001") //免费课程
                .createDate(LocalDateTime.now())
                .validDays(365)
                .status("701001") //选课成功
                .validtimeStart(LocalDateTime.now())
                .validtimeEnd(LocalDateTime.now().plusDays(365))
                .remarks(coursePublish.getRemark())
                .build();
        int insert = xcChooseCourseMapper.insert(xcChooseCourse);
        if (insert <= 0) {
            throw new RuntimeException("课程添加失败");
        }
        return xcChooseCourse;
    }

    //向课程表添加数据
    public XcCourseTables addCourseTabls(XcChooseCourse xcChooseCourse) {
        //查询选课状态
        String status = xcChooseCourse.getStatus();
        if (!"701001".equals(status)) {
            throw new RuntimeException("选课未成功，添加课程失败");
        }

        //查询我的课程表
        XcCourseTables xcCourseTables = getXcCourseTables(xcChooseCourse.getUserId(), xcChooseCourse.getCourseId());
        if (xcCourseTables != null) {
            return xcCourseTables;
        }

        XcCourseTables xcCourseTablesNew = new XcCourseTables();
        xcCourseTablesNew.setChooseCourseId(xcChooseCourse.getId());
        xcCourseTablesNew.setUserId(xcChooseCourse.getUserId());
        xcCourseTablesNew.setCourseId(xcChooseCourse.getCourseId());
        xcCourseTablesNew.setCompanyId(xcChooseCourse.getCompanyId());
        xcCourseTablesNew.setCourseName(xcChooseCourse.getCourseName());
        xcCourseTablesNew.setCreateDate(LocalDateTime.now());
        xcCourseTablesNew.setValidtimeStart(xcChooseCourse.getValidtimeStart());
        xcCourseTablesNew.setValidtimeEnd(xcChooseCourse.getValidtimeEnd());
        xcCourseTablesNew.setCourseType(xcChooseCourse.getOrderType());
        int insert = xcCourseTablesMapper.insert(xcCourseTablesNew);
        if (insert <= 0) {
            throw new RuntimeException("向课程表添加数据失败");
        }
        return xcCourseTablesNew;
    }

    /**
     * @param userId
     * @param courseId
     * @return com.xuecheng.learning.model.po.XcCourseTables
     * @description 根据课程和用户查询我的课程表中某一门课程
     * @author Mr.M
     * @date 2022/10/2 17:07
     */
    public XcCourseTables getXcCourseTables(String userId, Long courseId) {

        return xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>()
                .eq(XcCourseTables::getUserId, userId)
                .eq(XcCourseTables::getCourseId, courseId));

    }

    /**
     * @param userId
     * @param courseId
     * @return XcCourseTablesDto 学习资格状态 [{"code":"702001","desc":"正常学习"},{"code":"702002","desc":"没有选课或选课后没有支付"},{"code":"702003","desc":"已过期需要申请续期或重新支付"}]
     * @description 判断学习资格
     * @author Mr.M
     * @date 2022/10/3 7:37
     */
    @Override
    public XcCourseTablesDto getLearningStatus(String userId, Long courseId) {
        //查询我的课程表
        XcCourseTables xcCourseTables = getXcCourseTables(userId, courseId);
        if (xcCourseTables == null) {
            XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
            //没有选课或选课后没有支付
            xcCourseTablesDto.setLearnStatus("702002");
            return xcCourseTablesDto;
        }


        XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
        BeanUtils.copyProperties(xcCourseTables, xcCourseTablesDto);
        //是否过期,true过期，false未过期
        boolean isExpires = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        if (!isExpires) {
            //正常学习
            xcCourseTablesDto.setLearnStatus("702001");
            return xcCourseTablesDto;

        } else {
            //已过期
            xcCourseTablesDto.setLearnStatus("702003");
            return xcCourseTablesDto;
        }


    }

    /**
     * 保存选课成功状态
     *
     * @param chooseCourseId
     * @return
     */
    @Override
    public boolean saveChooseCourseSuccess(String chooseCourseId) {
        //根据选课id查询选课表
        XcChooseCourse xcChooseCourse = xcChooseCourseMapper.selectById(chooseCourseId);

        if (xcChooseCourse == null) {
            log.error("未找到选课记录,选课记录id:{}", chooseCourseId);
            return false;
        }
        String status = xcChooseCourse.getStatus();
        //"701002"为 未支付
        if ("701002".equals(status)) {
            xcChooseCourse.setStatus("701001");
            int result = xcChooseCourseMapper.updateById(xcChooseCourse);
            if (result <= 0) {
                XueChengPlusException.cast("修改选课状态失败");
                return false;
            }
            //向我的课程表插入记录
            XcCourseTables xcCourseTables = addCourseTabls(xcChooseCourse);
            return true;
        }
        return false;
    }

    /**
     * @param params
     * @return
     * @Desc: 获取我的课程表
     */
    @Override
    public PageResult<XcCourseTables> getCoursetable(MyCourseTableParams params) {
        //页码
        long pageNo = params.getPage();
        //每页记录数
        long pageSize = params.getSize();

        Page<XcCourseTables> page = new Page<>(pageNo, pageSize);

        LambdaQueryWrapper<XcCourseTables> wrapper = new LambdaQueryWrapper<XcCourseTables>()
                .eq(XcCourseTables::getUserId, params.getUserId());

        Page<XcCourseTables> result = xcCourseTablesMapper.selectPage(page, wrapper);
        if(result == null){
            XueChengPlusException.cast("获取课程表失败");
        }


        return new  PageResult(
                result.getRecords(),
                result.getTotal(),
                pageNo,
                pageSize
        );
    }
}
